package dw2;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Owner
 */
public class StandardJavaFileIO extends FileIO {

    @Override
    public boolean read() {
        try {
            Scanner scanner = new Scanner(this.getFile());
            LinkedList<User> listusers;
            while ((listusers = getUserList()) == null) {
                Thread.sleep(50);
            }
            while (scanner.hasNext()) {
                listusers.add(new User(scanner.next(), (int) scanner.useDelimiter("\t").nextDouble()));
                scanner.useDelimiter("\n");
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(StandardJavaFileIO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StandardJavaFileIO.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } finally {
            releaseList();
        }
        return true;
    }

    public boolean write(String username, double score) {
        try {
            BufferedWriter writer = null;
            LinkedList<User> listUsers;
            while ((listUsers = getUserList()) == null) {
            }
            listUsers.add(new User(username, (int) score));
            writer = new BufferedWriter(new FileWriter(this.getFile()));
            Iterator iterator;
            for(iterator = listUsers.listIterator(); iterator.hasNext();){
                writer.newLine();
                User user = (User)iterator.next();
                writer.write(user.getUsername() + "\t"+ Double.toHexString(user.getScore()));
            }
            return false;
        } catch (IOException ex) {
            Logger.getLogger(StandardJavaFileIO.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            releaseList();
        }
        return true;
    }

    public boolean write(String username, int score) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean write(String[] username, int[] score) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
